package logic

import (
	"context"
	"errors"
	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"
	"fresh-box/models/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line
	tx := mysql.DB.Debug().Begin()

	var findFresh mysql.Fresh
	tx.Where("name = ?", in.Name).Find(&findFresh)
	if findFresh.ID != 0 {
		return nil, errors.New("当前商品已经存在，请更换商品添加")
	}
	var class mysql.Class
	tx.Where("name = ?", in.Classname).Find(&class)

	if class.ID == 0 {
		class = mysql.Class{
			ClassName: in.Classname,
		}
		err := tx.Create(&class).Error
		if err != nil {
			tx.Rollback()
			return nil, errors.New("分类添加失败")
		}
	}

	fresh := mysql.Fresh{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		Info:    in.Info,
		ClassId: int64(class.ID),
	}
	err := mysql.DB.Debug().Create(&fresh).Error

	if err != nil {
		return nil, errors.New("商品添加失败")
	}

	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
